package com.jinzhi.jzweb.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.dao.*;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.JazMessageService;
import com.jinzhi.jzweb.service.MessageplatfromService;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sys.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

/**
 * 
 * <pre>
 * 消息表
 * </pre>
 * <small> 2024-05-13 10:25:49 | Long</small>
 */
@Service
public class JazMessageServiceImpl extends CoreServiceImpl<JazMessageDao, JazMessageDO> implements JazMessageService {

    @Autowired
    private JazUserDemandDao jazUserDemandDao;

    @Autowired
    private JazSysProjectDao jazSysProjectDao;

    @Autowired
    private JazInterviewDao jazInterviewDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SmsManager smsSerevice;

    @Autowired
    private JazUserOrderDao userOrderDao;

    @Autowired
    private JazGroupOrderDao jazGroupOrderDao;

    @Autowired
    private JazGroupProdDao jazGroupProdDao;

    @Autowired
    private DictService dictService;

    private final String CODE = "MSG";

    private final String ORDER_CODE = "MSG_ORDER";

    private final String USER = "MSG_USER";  //用户端专用

    private final String SIGN_NAME = "金职到家";

    /**
     * 发送消息通用接口
     * @param jazMessageDO
     */
    @Override
    public void senMessage(JazMessageDO jazMessageDO) {
        /**
         * redis key规则：code + 消息接收者id
         * MsgCodeEnum 枚举获取code
         */
        Assert.notNull(jazMessageDO.getMessageType(),"参数:messageType不能为空");
        Assert.notNull(jazMessageDO.getSenderId(),"参数:senderId不能为空");
        Assert.notNull(jazMessageDO.getReceiverId(),"参数:receiverId不能为空");
//        Assert.notNull(jazMessageDO.getObjectId(),"参数:objectId不能为空");
        //系统消息
        if(jazMessageDO.getMessageType() == 1){
            Assert.notNull(jazMessageDO.getMessageContent(),"参数:messageContent不能为空");
        }
        //订单消息
        else if (jazMessageDO.getMessageType() == 2) {
            //查询需求信息
            getDemand(jazMessageDO);
        }
        jazMessageDO.setCreateTime(new Date());
        //新增消息记录
        this.insert(jazMessageDO);
        //发送短信
        setTemplate(MessagesEnum.findByNum(jazMessageDO.getMessageNum()),jazMessageDO);

    }

    private void getDemand(JazMessageDO jazMessageDO) {
        JazInterviewDO jazInterviewDO = new JazInterviewDO();
        if(jazMessageDO.getInterviewId()==null){
            return;
        } else {
            jazInterviewDO = jazInterviewDao.selectById(jazMessageDO.getInterviewId());
        }
        if(null!=jazInterviewDO){
            //查询阿姨类型
            JazSysProjectDO jazSysProjectDO = jazSysProjectDao.selectById(jazInterviewDO.getProjectId());
            if(null!=jazSysProjectDO){
                jazInterviewDO.setProjectName(jazSysProjectDO.getName());
            }
            jazMessageDO.setJazInterviewDO(jazInterviewDO);
        }
    }

    /**
     * 消息轮询接口
     * @return
     */
    @Override
    public List<Object> messageList(Integer messageType,Long receiverId) {
//        Assert.notNull(receiverId,"参数:senderId不能为空");
//        List<Object> list = redisTemplate.opsForList().range(createKey(messageType,receiverId), 0, -1);
        return null;
    }

    /**
     * 首次查询消息列表 （获取数据库）
     * @param receiverId
     * @return
     */
    @Override
    public List<JazMessageDO> getMessage(Integer messageType,Long receiverId) {
        Assert.notNull(receiverId,"参数:senderId不能为空");
        EntityWrapper<JazMessageDO> wrapper = new EntityWrapper<>();
        wrapper.eq("receiver_id",receiverId);
        wrapper.orderBy("create_time",false);
        if (messageType!=3) {  //messageType == 3表示用户端，直接查全部。
            wrapper.eq("message_type", messageType);
        }
        List<JazMessageDO> messageDOList = this.selectList(wrapper);
        for (JazMessageDO messageDO:messageDOList){
            if (messageDO.getDemandId() != null){ //通过用户发布需求阿姨找工作
                messageDO.setMessageTypeUser(0);
            }else{ //直接发起邀约，没有绑定需求
                messageDO.setMessageTypeUser(1);
            }
        }

        //数据库 和 redis 数据保持同步
//        String key = createKey(messageType,receiverId);
        //删除旧数据
//        redisTemplate.delete(key);
        //插入新数据到redis
//        messageDOList.forEach(message->{
//           redisTemplate.opsForList().leftPush(key,message);
//        });

        return messageDOList;
    }




    /**
     * 用户端修改阅读状态
     */
    @Override
    public void changeUserRead(Long messageId) {
        //字段校验
        JazMessageDO jazMessageDO = this.selectById(messageId);
        jazMessageDO.setIsRead(1);
        this.updateById(jazMessageDO);
    }








    /**
     * 修改阅读状态
     * @param jazMessageDO
     */
    @Override
    public void changeRead(JazMessageDO jazMessageDO) {
        //字段校验
        Assert.notNull(jazMessageDO.getId(),"id"+"不能为空");
        jazMessageDO.setIsRead(1);
        this.updateById(jazMessageDO);
    }

    /**
     * 获取未读的消息数量
     * @return
     */
    @Override
    public Map<Integer, Integer> getMessageNum() {
        Long userId = JWTUtil.getUser().getId();
        Map<Integer, Integer> map = new HashMap<>();
        EntityWrapper<JazMessageDO> wrapper = new EntityWrapper<>();
        wrapper.eq("receiver_id",userId);
        wrapper.eq("is_read",0);
        List<JazMessageDO> jazMessageDOS = this.selectList(wrapper);
        int num1=0;
        int num2=0;
        if(null!=jazMessageDOS && !jazMessageDOS.isEmpty()){
            for (JazMessageDO jazMessageDO : jazMessageDOS) {
                if(jazMessageDO.getMessageType()==1){
                    num1 += 1;
                } else if (jazMessageDO.getMessageType()==2) {
                    num2 += 1;
                }
            }
        }
        map.put(1,num1);
        map.put(2,num2);
        return map;
    }

    /**
     * 订单消息详情
     * @param demandId 需求id
     * @param messageId 消息id
     * @return
     */
    @Override
    public JazMessageDO messageType2Detail(Long demandId,Long interviewId,Long messageId) {
        //查询消息信息

        /**
         * 考虑两种情况
         * 1.面试邀约没有需求，直接联系阿姨 （需求id为nulll），直接查邀约信息
         * 2.面试邀约有需求，需要先查看需求，再查询邀约信息
         */
        JazMessageDO jazMessageDO = this.selectById(messageId);
        if(null!=jazMessageDO){
            //查询需求信息
            getDemand(jazMessageDO);
            //查询邀约人和联系电话
            UserDO userDO = userDao.selectById(jazMessageDO.getJazInterviewDO().getInviterId());
            if(userDO!=null){
                jazMessageDO.getJazInterviewDO().setInviterName(userDO.getName());
                jazMessageDO.getJazInterviewDO().setInviterPhone(userDO.getOrderPhone());
                jazMessageDO.getJazInterviewDO().setSex(userDO.getSex().intValue());
            }
            if(jazMessageDO.getJazInterviewDO().getResult()==2){
                jazMessageDO.getJazInterviewDO().setInterStatus(2);
            }
        }

        return jazMessageDO;
    }

    /**
     * 生成key
     * @param messageType 消息类型
     * @param userId 消息接收者
     * @return
     */
    public String createKey(Integer messageType,Long userId){
        switch (messageType){
            case 1:return CODE+userId;
            case 2:return ORDER_CODE+userId;
            case 3:return USER+userId;
            default:return null;
        }
    }


    /**
     * 配置短信模版 发送短信
     * @param code 短信模版code
     * @param jazMessageDO 消息信息
     */
    public void setTemplate(String code,JazMessageDO jazMessageDO){
        /** 判断是否需要发送短信 */
        try{
            if(jazMessageDO.isHasSendSms()){
                Map map = new HashMap();
                //查询用户
                UserDO userDO = userDao.selectById(jazMessageDO.getReceiverId());
                if(userDO.getName() != null){
                    map.put("name",userDO.getName());
                } else {
                    map.put("name",userDO.getUsername());
                }


                /**
                 * 配置不用短信内容
                 */
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                //服务订单通知
                if(MessagesEnum.MESSAGE_110.getCode().equals(code) || MessagesEnum.MESSAGE_111.getCode().equals(code)){
                    map.put("phone",getCustomer());
                    JazUserOrderDO jazUserOrderDO = userOrderDao.selectById(jazMessageDO.getUserOrderId());
                    map.put("time1",sf.format(jazUserOrderDO.getStartTime()));
                    map.put("time2",sf.format(jazUserOrderDO.getEndTime()));
                }
                //商品到期通知
                else if (MessagesEnum.MESSAGE_112.getCode().equals(code)) {
                    //查询团购订单
                    JazGroupOrderDO jazGroupOrderDO = jazGroupOrderDao.selectById(jazMessageDO.getGroupOrderId());
                    //查询团购商品
                    JazGroupProdDO jazGroupProdDO = jazGroupProdDao.selectById(jazGroupOrderDO.getGroupProdId());
                    //计算到期时间
                    Date date = addDateDay(jazGroupOrderDO.getCreateTime(), jazGroupProdDO.getValidTime() * 30);
                    map.put("time",sf.format(date));
                }
                //邀约阿姨面试通知
                else if (MessagesEnum.MESSAGE_204.getCode().equals(code)) {
                    JazInterviewDO jazInterviewDO = jazInterviewDao.selectById(jazMessageDO.getInterviewId());
                    map.put("time",sf.format(jazInterviewDO.getInterviewTime()));
                }
                //分配服务订单 || 服务转让
                else if (MessagesEnum.MESSAGE_208.getCode().equals(code) || MessagesEnum.MESSAGE_206.getCode().equals(code)) {
                    JazUserOrderDO jazUserOrderDO = userOrderDao.selectById(jazMessageDO.getUserOrderId());
                    map.put("time",sf.format(jazUserOrderDO.getStartTime()));
                }
                System.out.println("消息发送=================== 电话："+userDO.getMobile()+" code："+code+ " map："+map);
                smsSerevice.send1(userDO.getMobile(), code, SIGN_NAME, map);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Date addDateDay(Date date,int day){
        // 使用Calendar添加天数
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);

        // 获取新的Date对象
        return calendar.getTime();
    }

    public String getCustomer(){
        String customer = "19918316230";//客服电话
        Map map = new HashMap();
        map.put("Type","customer_sms");
        List<DictDO> dictDOS = dictService.selectListBy(map);
        if(dictDOS!=null && !dictDOS.isEmpty()){
            customer = dictDOS.get(0).getValue();
        }
        return customer;
    }


}
